import { useState } from 'react';
import {
  Layout,
  Dropdown,
  Modal,
  Form,
  Input,
  Popconfirm,
  message,
  Space,
} from 'antd';
import { useNavigate } from 'react-router-dom';
import { UserOutlined, CaretDownOutlined } from '@ant-design/icons';
import { useRequest } from 'ahooks';
import type { MenuProps } from 'antd';

import { loginOutAPI, updatePasswordAPI } from '@/api/login';
import Icon from '@/components/SvgIcon';
import Logo from '@/assets/image/logo1.png';
import './index.scss';

const { Header } = Layout;

const LayoutHeader: React.FC = () => {
  let navigate = useNavigate();
  const [form] = Form.useForm();
  const values = Form.useWatch([], form);
  const [isModalOpen, setIsModalOpen] = useState(false);

  const { run: backToLogin } = useRequest(() => loginOutAPI(), {
    manual: true,
    onSuccess: () => {
      navigate('/login');
      // localStorage.removeItem('loginInfo');
      localStorage.removeItem('satoken');
    },
    onError: err => {
      console.log(err);
    },
  });

  const handleOk = () => {
    form
      .validateFields()
      .then(() => updatePassword())
      .catch(err => {
        console.log(err);
        return;
      });
  };

  const handleCancel = () => {
    form.setFieldsValue({
      oldPassword: '',
      newPassword: '',
      beSurePassword: '',
    });
    setIsModalOpen(false);
  };

  const { run: updatePassword } = useRequest(
    () =>
      updatePasswordAPI({
        newPassword: values.newPassword,
        oldPassword: values.oldPassword,
      }),
    {
      manual: true,
      onSuccess: (res: any) => {
        if (res.success) {
          message.success('修改成功!');
          handleCancel();
          navigate('/login');
        }
      },
    }
  );

  const items: MenuProps['items'] = [
    {
      label: <div onClick={() => setIsModalOpen(true)}>修改密码</div>,
      key: '0',
    },
    {
      label: (
        <Popconfirm
          title="退出登录"
          description="确认退出登录?"
          onConfirm={backToLogin}
          okText="确认"
          cancelText="取消">
          <div>退出登录</div>
        </Popconfirm>
      ),
      key: '1',
    },
  ];

  const loginInfo = localStorage.getItem('loginInfo');
  const userName = loginInfo && JSON.parse(loginInfo).userName;

  return (
    <div>
      <Header className="header">
        <div
          style={{
            display: 'flex',
            alignItems: 'center',
            cursor: 'pointer',
          }}>
          <img src={Logo} alt="logo" width="48" />
          <h1 style={{ marginLeft: '8px' }}>{process.env.REACT_APP_TITLE}</h1>
        </div>
        <Dropdown className="dropMenu" menu={{ items }}>
          <Space>
            <UserOutlined />
            <span>{userName}</span>
            <CaretDownOutlined />
          </Space>
        </Dropdown>
      </Header>

      <Modal
        title="修改密码"
        centered
        open={isModalOpen}
        onOk={handleOk}
        onCancel={handleCancel}>
        <Form className="form" form={form} layout="vertical">
          <Form.Item
            name="oldPassword"
            label="请输入原密码"
            required={true}
            rules={[{ required: true, message: '请输入原密码' }]}>
            <Input.Password
              placeholder="请输入原密码"
              iconRender={visible => (
                <div style={{ color: '#d9d9d9' }}>
                  {visible ? (
                    <Icon name="icon-zhengyan" />
                  ) : (
                    <Icon name="icon-biyan" />
                  )}
                </div>
              )}
            />
          </Form.Item>
          <Form.Item
            name="newPassword"
            label="请输入新密码"
            required={true}
            tooltip={`新密码不可和原密码相同。密码复杂度必须包含英文大写字母、小写字母、数字和特殊符号!、@、#、$、%、^、&、*、.且长度不少于8位`}
            rules={[
              // { required: true },
              {
                validator: (_, value) => {
                  console.log('===>', value, _);
                  if (value) {
                    if (value !== values.oldPassword) {
                      return Promise.resolve();
                    } else {
                      return Promise.reject('新密码不能与原密码相同');
                    }
                  } else {
                    return Promise.reject('请输入新密码');
                  }
                },
              },
            ]}>
            <Input.Password
              placeholder="请输入新的密码"
              iconRender={visible => (
                <div style={{ color: '#d9d9d9' }}>
                  {visible ? (
                    <Icon name="icon-zhengyan" />
                  ) : (
                    <Icon name="icon-biyan" />
                  )}
                </div>
              )}
            />
          </Form.Item>
          <Form.Item
            name="beSurePassword"
            label="请确认新密码"
            required={true}
            rules={[
              // { required: true },
              {
                validator: (_, value) => {
                  if (value) {
                    if (value === values.newPassword) {
                      return Promise.resolve();
                    } else {
                      return Promise.reject('两次密码不同');
                    }
                  } else {
                    return Promise.reject('请确认新密码');
                  }
                },
              },
            ]}>
            <Input.Password
              placeholder="请确认新的密码"
              iconRender={visible => (
                <div style={{ color: '#d9d9d9' }}>
                  {visible ? (
                    <Icon name="icon-zhengyan" />
                  ) : (
                    <Icon name="icon-biyan" />
                  )}
                </div>
              )}
            />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default LayoutHeader;
